<?php

namespace app\controller\adminapi;

use app\controller\adminapi\cloud\Cloud;
use think\App;
use app\common\services\facade\Upgrade;
use hiduoke\services\CloudServer;
use app\common\model\visit\Visit;
use app\common\model\platform\Platform;
use app\common\controller\AdminController;
use think\facade\Cache;
use think\facade\Env;

class Dashboard extends AdminController
{
    /**
     * @var string[] 无需登录的action
     */
    protected $notLogin = [];
    protected $notCheck = [];

    /**
     * @var Platform
     */
    private Platform $platformModel;


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->platformModel = new Platform();
    }


    /**
     * @return \think\response\Json
     */
    public function index()
    {
        $data = ['loading' => true];
        $platform = $this->platformModel->field('count(*) as count,type')->group('type')->select();
        foreach ($platform as $key => $value) {
            $data['platform'][$value['type']] = $value['count'];
        }
        return $this->success('ok', $data);
    }

    /**
     * 访问数量
     * @return \think\response\Json
     */
    public function getVisit()
    {
        $visit = new Visit();
        $data = $visit->getVisitListForDashboard();
        return $this->success('ok', $data);
    }

    public function getFooterMsg()
    {
        $data = [
            'newList' => $this->getNewList(1, 6),
            'ad'      => $this->getNewList(2, 3),
            'system'  => $this->getSystem(),
            'update'  => $this->getUpdate()
        ];
        return $this->success('', $data);
    }

    /**
     * 动态
     */
    private function getNewList($status = 1, $count = 6)
    {
        $cache_key = "getNewList-" . $status;
        $data = Cache::get($cache_key);
        if ($data) {
            return $data;
        }
        $cloud = new CloudServer();
        $ads = $cloud->getAdList($status, $count);
        if ($ads['code'] == 0) {
            $data = $ads['data'];
            foreach ($data as $key => $value) {
                $data[$key]['datetime'] = date("m-d", $value['datetime']);
            }
            Cache::set($cache_key, $data);
            return $data;
        } else {
            return [];
        }
    }

    private function getSystem()
    {
        $data = [
            "version"     => Upgrade::getVersion()['version'],
            'php_version' => PHP_VERSION,
            'server'      => @$_SERVER['SERVER_SOFTWARE'],//TODO 这里如果是swoole启动就没有这个要报错
            'debug'       => $this->request->env('APP_DEBUG')
        ];

        return $data;
    }

    private function getUpdate()
    {
        $data = Cache::get('getUpdate');
        if (!$data) {
            $data = [];
            $version = Upgrade::getVersion()['version'];
            $data['sys_update'] = (new CloudServer())->getUpdateProgram($version)['data'] ?? [];
            $addon_update_msg = (new \app\common\model\addon\Addons())->getAddonUpdateMsg();
            $addon_names = [];
            foreach ($addon_update_msg as $key => $value) {
                $addon_names[] = $key;
            }
            $addons = (new \app\common\model\addon\Addons())->whereIn('name', $addon_names)->append(['new_version', 'is_update'])->select();
            $data['addon_update'] = [];
            foreach ($addons as $key => $value) {
                if ($value['is_update']) {
                    $data['addon_update'][] = $value;
                }
            }
            Cache::set('getUpdate', $data,3600);
        }
        return $data;
    }

    /**
     * 修改配置文件
     * @param array $a
     * @param array $parent
     * @return string
     */
    private function arr_trinsform_ini(array $a, array $parent = array())
    {
        $out = '';
        $keysindent = [];
        foreach ($a as $k => $v) {
            if (is_array($v)) {
                $sec = array_merge((array)$parent, (array)$k);
                $out .= '[' . join('.', $sec) . ']' . PHP_EOL;
                $out .= $this->arr_trinsform_ini($v, $sec);
            } else {
                $key = explode('_', $k);
                if (count($key) > 1 && !in_array($key[0], $keysindent)) {
                    $keysindent[] = $key[0];
                    $out .= PHP_EOL;
                    $out .= "[$key[0]]" . PHP_EOL;
                    unset($key[0]);
                    $out .= implode('_', $key) . " = $v" . PHP_EOL;
                    //unset($key);
                } elseif (count($key) > 1 && in_array($key[0], $keysindent)) {
                    unset($key[0]);
                    $out .= implode('_', $key) . " = $v" . PHP_EOL;
                } else {
                    $out .= "$k = $v" . PHP_EOL;
                }
            }
        }
        return $out;
    }

    public function setSystemDebug()
    {
        Env::offsetSet('APP.DEBUG', env('app_debug') ? 'false' : 'true');
        $envPath = root_path() . DIRECTORY_SEPARATOR . '.env';
        $envinidata = Env::get();
        $inicontent = $this->arr_trinsform_ini($envinidata);
        $fp = fopen($envPath, "w") or die("Couldn't open $envPath");
        fputs($fp, $inicontent);
        fclose($fp);
        return $this->success("修改成功", env('app_debug'));
    }
}
